import { BeforeInsert, Column, Entity, PrimaryGeneratedColumn } from 'typeorm'
import * as bcrypt from 'bcryptjs'

@Entity('user')
export class UserEntity {
  @PrimaryGeneratedColumn()
  id: number

  @Column({ length: 100, nullable: true })
  account: string

  @Column({ length: 100 })
  nickname: string

  @Column()
  password: string

  @Column({ default: '' })
  avatar: string

  @Column({ default: '', nullable: true })
  email: string

  @Column({ default: '', nullable: true })
  phone: string

  @Column({ type: 'tinyint', comment: '角色: 1超级管理员, 2管理员, 3顾客', default: 3 })
  role: number  // 用户角色

  @Column({
    type: 'decimal', precision: 10, scale: 2, comment: '饭币', transformer: {
      to: (value: number) => value,
      from: (value: string) => Number.parseFloat(value),
    }
  })
  balance: number

  @Column({ default: Math.floor(Date.now() / 1000) })
  create_time: number

  @Column({ default: Math.floor(Date.now() / 1000) })
  update_time: number

  @BeforeInsert()
  async encryptPwd() {
    this.password = await bcrypt.hashSync(this.password)
  }
}
